import {
  Card,
  Tree,
  Row,
  Col,
  Pagination,
  Tag,
  Table,
  Button,
  message,
} from 'antd'
import type { TreeProps } from 'antd/lib/tree'
import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import {
  reqDepartment,
  reqBookingScheduleList,
  reqScheduleController,
} from '@api/hospital/hospitalList'
import {
  IdepartmentType,
  IworkDate,
  IsheduleControllerType,
} from '@api/hospital/model/hospitalListTypes'
import { use } from 'i18next'

export default function HospitalListSchedule() {
  const navigate = useNavigate()
  const { hoscode } = useParams()
  const [hosname, setHosname] = useState('')
  const [depname, setDepname] = useState('')
  const [department, setDepartment] = useState<IdepartmentType>([])
  const [depcodeList, setDepcodeList] = useState<string[]>([])
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)
  const [bookingScheduleList, setBookingScheduleList] = useState<IworkDate[]>(
    []
  )
  const [depcode, setDepcode] = useState('')
  const [workDate, setWorkDate] = useState('')
  const [scheduleController, setScheduleController] =
    useState<IsheduleControllerType>([])

  const onSelect: TreeProps['onSelect'] = async (selectedKeys, info: any) => {
    const depcode = selectedKeys[0]
    setDepcode(depcode as string)
    const workDate = await getBookingScheduleList(
      page,
      pageSize,
      depcode as string
    )
    if (!workDate) {
      return
    }
    getScheduleController(depcode as string, workDate)
    setDepname(info.node.depname)
  }

  const columns = [
    {
      title: '序号',
      render: (text: any, record: any, index: number) => {
        return index + 1
      },
    },
    {
      title: '职称',
      dataIndex: 'title',
    },
    {
      title: '号源时间',
      dataIndex: 'workDate',
    },
    {
      title: '可预约数',
      dataIndex: 'availableNumber',
    },
    {
      title: '剩余预约数',
      dataIndex: 'reservedNumber',
    },
    {
      title: '挂号费(元)',
      dataIndex: 'amount',
    },
    {
      title: '擅长技能',
      dataIndex: 'skill',
    },
  ]

  async function getDepartment() {
    const result = await reqDepartment(hoscode as string)
    result.forEach((item) => (item.disabled = true))
    setDepartment(result)
    setDepcodeList(result.map((item) => item.depcode))
    return result[0].children[0].depcode
  }

  //获取Tag组件的排班日期数据
  async function getBookingScheduleList(
    page: number,
    pageSize: number,
    depcode: string
  ) {
    const result = await reqBookingScheduleList(
      page,
      pageSize,
      hoscode as string,
      depcode
    )

    if (!result.total) {
      setBookingScheduleList([])
      setScheduleController([])
      setWorkDate('')
      setDepname('')
      setTotal(0)
      message.error('暂无数据')
      return ''
    }
    setWorkDate(result.bookingScheduleList[0].workDate)
    setTotal(result.total)
    setBookingScheduleList(result.bookingScheduleList)
    return result.bookingScheduleList[0].workDate
  }

  //获取Table组件的每日医生预约数据
  async function getScheduleController(depcode: string, workDate: string) {
    const result = await reqScheduleController(
      hoscode as string,
      depcode,
      workDate
    )
    setScheduleController(result)
    return result[0]
  }

  useEffect(() => {
    async function fetchData() {
      const depcode = await getDepartment()
      setDepcode(depcode)
      const workDate = await getBookingScheduleList(page, pageSize, depcode)
      const result = await getScheduleController(depcode, workDate as string)
      const hosname = result.param.hosname
      const depname = result.param.depname
      setHosname(hosname)
      setDepname(depname)
    }
    fetchData()
  }, [])

  const treeHight = document.body.clientHeight - 64 - 34 - 24 * 2 - 22
  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      <Row gutter={20}>
        <Col span={5}>
          <div style={{ border: '1px solid #ccc', overflow: 'auto' }}>
            <Tree
              style={{ height: treeHight }}
              onSelect={onSelect}
              treeData={department as any}
              fieldNames={{ title: 'depname', key: 'depcode' }}
              expandedKeys={depcodeList}
            />
          </div>
        </Col>
        <Col span={19}>
          {bookingScheduleList.map((item, index) => {
            return (
              <Tag
                key={index}
                color={item.workDate === workDate ? 'green' : ''}
                style={{ marginBottom: 10, cursor: 'pointer' }}
                onClick={() => {
                  setWorkDate(item.workDate)
                  getScheduleController(depcode, item.workDate)
                }}
              >
                <div>{item.workDate + ' ' + item.dayOfWeek}</div>
                <div>{item.availableNumber + ' / ' + item.reservedNumber}</div>
              </Tag>
            )
          })}
          <Pagination
            total={total}
            current={page}
            pageSize={pageSize}
            showSizeChanger={true}
            style={{ marginBottom: 10 }}
            pageSizeOptions={['5', '10', '15', '20']}
            onChange={async (page, pageSize) => {
              setPage(page)
              setPageSize(pageSize)
              const workDate = await getBookingScheduleList(
                page,
                pageSize,
                depcode
              )
              getScheduleController(depcode, workDate as string)
            }}
          ></Pagination>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={scheduleController}
            bordered
            pagination={false}
          ></Table>
          <Button
            style={{ marginTop: 20 }}
            onClick={() => {
              navigate(-1)
            }}
          >
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  )
}
